<template>
    <div class="scene_root">
		<!-- :style="{cursor:!isEdit?'': 'not-allowed'}" -->
				<!-- cursor: pointer;
		cursor: not-allowed -->
        <!-- <div class="btn_lay">
            <el-button @click="resetView()">resetView</el-button>
            <el-button @click="getCurrentView()">currentView</el-button>

            <el-button @click="setSelectBallMarker(1)">ballMarker1</el-button>
            <el-button @click="setSelectBallMarker(2)">ballMarker2</el-button>
            <el-button @click="setSelectBallMarker(3)">ballMarker3</el-button>

        </div> -->

        <!-- <div class="click_point_lay">
            多选的构件
            <div class="array_lay">
                <el-tag
                    v-for="tag in mSelectElementArray"
                    :key="tag"
                    closable
                    @click="onTagClick(tag)"
                    @close="onTagCloseClick(tag)"
                    style="margin:3px"
                >
                    {{ tag }}
                </el-tag>
            </div>
        </div> -->

		<div class="topScan">
			<span>3D CADモデル</span>
			<div class="form-row-right-content">
				<el-select
					v-model="processorIndex"
					:placeholder="$t('message.bhView.label.placeholderSearch')"
					class="form-ipt"
				>
					<el-option
						v-for="(item, index) in processorData"
						:key="item.proCode"
						:label="item.proName"
						:value="index"
					></el-option>
				</el-select>
			</div>
			<span class="iconfont " :class="!isEdit?'isActive':''" @click="changeEdit">&#xec7c;</span>
		</div>
        <div v-if="mPercentNum < 100" id="percent">{{ mPercentNum }}%</div>
        <div id="scene_view" class="scene_view"></div>
    </div>
</template>

<script>
import threeData from "@/utils/testThreeData.js";
import { getProcessor } from "@/api/api";
import eventBus from "@/eventBus/bus";
export default {
	props: {
		isEdit: Boolean
	},
    data() {
        //数据
        return {
			processorIndex: 0,
			processorData: [],
            mModelUrl: "",
            mModelId: "",

            mInitViewPort: "",

            // 加载百分比
            mPercentNum: 0,

            mMarkerArray: [],
            mSelectElementArray: [],

            mSelectedBallMarkerId: -1,
            isLodFinish: false,
            tempColorPartsAfterLod: [],
            coloredPartsIds:'',
            tempVisiblePartsAfterLod: [],
            visibledPartsIds:'',
        };
    },

    methods: {
		//处理系一览
		getProcessorApi() {
			let dataJson = {
				pltCode:
					this.$store.state.threeRelationPltCode == ""
						? 0
						: this.$store.state.threeRelationPltCode,
			};
			getProcessor(dataJson).then((res) => {
				console.log(res,"FFFFFFFFFFFf")
				this.processorData = [];
				if (res.data.code != 0) {
					return;
				}
				this.processorData = res.data.data;
				this.processorChange(0);
			});
		},
		changeEdit(){
			this.$emit("changeEdit")
		},
        initEngineAndScene(inModelUrl, inModelId, inInitViewPort , inBgColor) {
            ZW_LoadNum0 = 0;
            this.mModelUrl = inModelUrl;
            this.mModelId = inModelId;
            this.mInitViewPort = inInitViewPort;

            AddModel(this.mModelUrl, this.mModelId, 1.25);
            EngineConfig("scene_view", false);
            SetShowNum(30000); //控制每次动态加载的切片数量，如果觉得加载时间长就调小一点
            if(inBgColor)
                SetBackColor(inBgColor[0],inBgColor[1],inBgColor[2], 1.0);
            else 
                SetBackColor(164, 178, 188, 1.0);

            SetPanSpeed(0.2);
        },

        /**
         * 模型加载完成
         */
        onModelLoaded(inV) {
            console.log(`--- OnModelLoaded --- ${inV}`);
            let _self = this;
            if (inV === "tag") return;
            this.resetView();
			
			//通知列表重新选择第一条
        },

        /**
         * 重置camera模式及位置
         */
        resetView() {
            SetCameraMode(0);
            SetView(this.mInitViewPort);
        },

        /**
         * 重置所有选中的构件颜色
         */
        resetAllSelectParts() {
            ResetAllElement();
        },

        /**
         * 重置所有选中的构件颜色
         */
        setElemnetColor(inId, inColorR = 255, inColorG = 0, inColorB = 0) {
            SetElementColor(inId, inColorR, inColorG, inColorB);
        },

        /**
         * 设置构件可见性
         * inId: 设置的ids
         * isV：是否可见  根据isReverse来确定
         * isReverse：是否反选；isReverse = true  全场景可见性取反
         */
        setElemnetVisible(inId, isV = true, isReverse = true) {
            // SetElementVisible(inId, isV , true);
            SetElementVisible(inId, isV, isReverse);
        },

        /**
         * 重置指定ids
         */
        resetElement(inId) {
            ResetElement(inId);
        },

        /**
        设置一堆位号颜色
         */
        setElemnetsColorsAndResetOther(inDataList) {
            if(!this.isLodFinish) {
                this.tempColorPartsAfterLod = inDataList
                return;
			}
            let _self = this;
            if(this.coloredPartsIds.length > 0)
                this.resetElement(this.coloredPartsIds)
            let ids = "";
            inDataList.forEach((element, index) => {
                ids += element;
                if (index < inDataList.length - 1) ids += "#";
            });
            this.setElemnetColor(ids);
            this.coloredPartsIds = ids;
        },

        setElementVisibleAndResetOther(inDataList) {
            if(!this.isLodFinish) {
                this.tempVisiblePartsAfterLod = inDataList
                return;
            }
            let _self = this;
            if(this.visibledPartsIds.length > 0)
                this.resetElement(this.visibledPartsIds)
            let ids = "";
            inDataList.forEach((element, index) => {
                ids += element;
                if (index < inDataList.length - 1) ids += "#";
            });
            this.setElemnetVisible(ids, false, true);
            this.flyTo3DNumber(ids);
            this.visibledPartsIds = ids;
        },

        /**
         * camera飞去指定位号
         */
        flyTo3DNumber(tag) {
            FlyTo(tag, true, 2.8);
        },

        /**
         * 模型加载过程，进度inV
         */
        onLoadModelProcess(inV) {
            this.mPercentNum = Math.ceil(inV * 100);
        },

        setSelectBallMarker(inId) {
            this.toSelect3dBallMarker(inId);
        },

        /**
         * 获取当前视口数据
         */
        getCurrentView() {
            this.$notify({
                title: "提示",
                message: GetView(),
                duration: 3000,
            });
        },

        /**
         * 点击位置
         */
        onClickPosition(position) {
            console.log("onClickPosition " + position);
            this.$emit("onClickPosition", position);
        },

        /**
         * 点击构件回调
         */
        onElementSelected(id) {
            console.log("构件id---" + id);
            this.$emit("onElementClick", id);
        },

        /**
         * 点击空白
         */
        onClickBlank() {
            console.log("--- onClickBlank ---");
            ResetAllElement();
        },

        /**
         * 添加球标
         * type circle  diamond  square
         */
        addBallLabel(
            inId,
            inStr,
            inShapeType,
            inPos,
            inFillColor,
            inBorderColor,
            defaultSelect = false
        ) {
            console.log("addLabel");
            let htmlStr = "";
            htmlStr += ` <div id="ball_label_${inId}" class="scene_ball" onclick="onBallMarkerClick(${inId},${inStr})">`;
            htmlStr += `     <div class="ball_${inShapeType} ${ defaultSelect ? 'arrow_box' : '' }" style="background: ${inFillColor}; "> `;
            htmlStr += `       <p class="${
                inShapeType == "diamond"
                    ? "ball_diamond_text"
                    : "ball_common_text"
            }">${inStr}</p> `; //
            htmlStr += `     </div> `;
            htmlStr += `     <div class="${
                defaultSelect ? "ball_line_select ball_line" : "ball_line"
            }"/>`;
            htmlStr += `</div> `;

            // let tempCurrentPos = GetCenterById(glids);

            AddHtmlMarker(inPos, htmlStr, "marker_" + inId);

            this.mMarkerArray.push({
                id: inId,
                text: inStr,
                shape: inShapeType,
                position: inPos,
                fillColor: inFillColor,
                borderColor: inBorderColor,
            });

            if (defaultSelect) {
                this.mSelectedBallMarkerId = inId;
            }
        },

        /**
         * 削除球标 by  id
         */
        removeAllBallMarkers() {
            ClearMarker();
            this.mMarkerArray = [];
        },

        removeMarkerSelected() {
            let temp = this.mSelectedBallMarkerId;
            this.removeMarkerById(this.mSelectedBallMarkerId);
            this.mSelectedBallMarkerId = -1;
            return temp;
        },

        removeMarkerById(inId) {
            if (inId >= 0) {
                let selectedBallIndex = this.mMarkerArray.findIndex(
                    (item, index) => {
                        return item.id == inId;
                    }
                );

                if (selectedBallIndex >= 0)
                    this.mMarkerArray.splice(selectedBallIndex, 1);

                RemoveMarker("marker_" + inId);
            }

            if (this.mSelectedBallMarkerId == inId)
                this.mSelectedBallMarkerId = -1;
        },

        /**
         * 点击球标
         */
        onBallMarkerClick(eid, estr) {
            console.log(`---!!!--- onLabelClick --- `, eid, estr);
            //     this.$notify({
            //         title: "提示",
            //         message: "onLabelClick()",
            //         duration: 3000,
            //     });
            this.$emit("onBallMarkerClick", eid, estr);
        },

        toSelect3dBallMarker(inId) {
            let tempBallData = this.mMarkerArray.find((item, index) => {
                return item.id == inId;
            });

            if (this.mSelectedBallMarkerId >= 0) {
                let selectedBallData = this.mMarkerArray.find((item, index) => {
                    return item.id == this.mSelectedBallMarkerId;
                });

                if (selectedBallData) {
                    let ballParent = document.getElementById(
                        "ball_label_" + selectedBallData.id
                    );
                    let ballBody = ballParent.getElementsByClassName(
                        `ball_${selectedBallData.shape}`
                    )[0];
                    ballBody.className = `ball_${selectedBallData.shape}`;
                //     ballBody.style[
                //         "border-color"
                //     ] = `${selectedBallData.borderColor}`;

                    let ballLine =
                        ballParent.getElementsByClassName(`ball_line`)[0];
                    ballLine.className = "ball_line";
                }
            }

            if (tempBallData) {
                let tempBallParent = document.getElementById(
                    "ball_label_" + tempBallData.id
                );
                let tempBallBody = tempBallParent.getElementsByClassName(
                    `ball_${tempBallData.shape}`
                )[0];
                // tempBallBody.style["border-color"] = `red`;
                tempBallBody.className = `ball_${tempBallData.shape} arrow_box`;

                let tempBallLine =
                    tempBallParent.getElementsByClassName(`ball_line`)[0];
                tempBallLine.className = "ball_line ball_line_select";
            }

            this.mSelectedBallMarkerId = inId;
        },

        onLodFinish() {
            console.log("onLodFinish --- onLodFinish --- onLodFinish")
            console.log(this.tempColorPartsAfterLod)
            console.log(this.tempVisiblePartsAfterLod)
			this.isLodFinish = true;
			this.$message({
				type: 'success',
				message: 'ロードが完了しました'
			})
			eventBus.$emit('getOneData')
			// alert("isLodFinish")

            if(this.tempColorPartsAfterLod.length > 0) {
                // this.setElemnetsColorsAndResetOther(this.tempColorPartsAfterLod)
                this.tempColorPartsAfterLod = [];
            }

            if(this.tempVisiblePartsAfterLod.length > 0) {
                // this.setElementVisibleAndResetOther(this.tempVisiblePartsAfterLod)
                this.tempVisiblePartsAfterLod = [];
            }
        }
    },

    created() {
		this.getProcessorApi();

        let _self = this;
        window["OnLoadModelProcess"] = (inV) => {
            _self.onLoadModelProcess(inV);
        };

        window["OnModelLoaded"] = (inV) => {
            _self.onModelLoaded(inV);
        };

        window["OnClickPosition"] = (inV) => {
            _self.onClickPosition(inV);
        };

        window["OnElementSelected"] = (inV) => {
            // _self.onElementSelected(inV);
			if(!this.isEdit){
				_self.onElementSelected(inV);
			}
        };

        window["OnClickBlank"] = (inV) => {
            _self.onClickBlank();
        };

        window["onBallMarkerClick"] = (inV, inS) => {
            _self.onBallMarkerClick(inV, inS);
        };

        window["OnLodFinish"] = (inV, inS) => {
            _self.onLodFinish();
        };

        
    },

    mounted() {},
};
</script>

<style lang="scss">
.scene_root {
        position: relative;
    //     display: flex;
    //     flex-direction: column;
    //     width: 100%;
    //     height: 100%;
    //     //   background: rgb(32, 93, 174);

}


.scene_view {
    //     width: 100%;
    height: 100%;
    overflow: hidden;
}

#percent {
    font-size: 35px;
    line-height: 100px;
    text-align: center;
    width: 100px;
    height: 100px;
    position: absolute;
    top: 40%;
    left: 50%;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.7);
    border: 2px solid rgb(56, 62, 150);
}

.scene_ball {
    position: relative;
    width: 30px;
    height: 30px;
    bottom: 30px;

    .ball_circle {
        width: 30px;
        height: 30px;
        border-radius: 50%;
        background: rgb(127, 251, 250);
        border: 2px solid #0600ff;
        
        text-align: center;
        display: flex;
        flex-direction: column;
        justify-content: center;
    }

    .ball_square {
        width: 30px;
        height: 30px;
        background: rgb(125, 253, 125);
        border: 2px solid #0600ff;

        text-align: center;
        display: flex;
        flex-direction: column;
        justify-content: center;
    }

    .ball_diamond {
        width: 30px;
        height: 30px;
        transform: rotateZ(45deg);
        /* clip-path: polygon(50% 0,100% 50%,50% 100%,0 50%); */
        background: rgb(255, 255, 68);
        border: 2px solid #0600ff;
        z-index: 100;

        text-align: center;
        display: flex;
        flex-direction: column;
        justify-content: center;
        text-transform: rotateZ(-45deg);
    }

    .ball_line {
        // border: 1px solid rgb(56, 62, 150);
        background: #0600ff;
        margin: 0 auto;
        height: 20px;
        width: 2px;
    }

    .ball_diamond_text {
        transform: rotateZ(-45deg);
    }

    .ball_common_text {
        transform: rotateZ(0deg);
    }

    .ball_line_select {
        background: rgb(255, 0, 0);
    }

    .ball_body_select {
        border: 2px solid rgb(255, 0, 0);
    }

    .arrow_box {
        animation: glow 800ms ease-out infinite alternate;
    }
    @keyframes glow {
        0% {
            border-color: #ff0000;
            box-shadow: 0 0 5px rgba(255, 0, 0, 0.2),
                inset 0 0 5px rgba(255, 0, 0, 0.1), 0 1px 0 #ff0000;
        }
        100% {
            border-color: #990000;
            box-shadow: 0 0 20px rgba(255, 0, 0, 0.6),
                inset 0 0 10px rgba(255, 0, 0, 0.4), 0 1px 0 #ff0000;
        }
    }
}
.topScan {
	width: 100%;
	max-height: 24px;
	display: flex;
	align-items: center;
	margin-bottom: 12px;
	// * {
	// 	padding-right: 20px;
	// }
	.form-row-right-content {
		width: 220px;
		margin: 0  25px 0 25px;
		.form-ipt {
			width: 100%;
			height: 24px;
			input {
				height: 24px;
				line-height: 24px;
			}
			.el-input__icon {
				line-height: 24px;
			}
		}
	}
}

.iconfont {
	font-size: 24px;
	cursor: pointer;
}
.isActive {
	color: #df1222;
}
</style>